import getpass
import subprocess
from sqlalchemy import create_engine
import toml
import pandas as pd
from datetime import datetime,timedelta,time,timezone
from dateutil.relativedelta import relativedelta


coin2_feed_stats_importer_config = {
    "host": "coin-db.corp.prestolabs.io",
    "database": "feed_stat_20200803",
    "user": "feed_stat_querier",
    "password": "#dXfc%DGtXg%SfBX"
}

user = getpass.getuser()
git_root_path = subprocess.Popen(['git', 'rev-parse', '--show-toplevel'], stdout=subprocess.PIPE).communicate()[0].rstrip().decode('utf-8')
git_root_path = git_root_path if git_root_path else f"/home/{user}/workspace/coin"
subscribers_path = f'{git_root_path}/data/coin2/feed/subscribers.toml'
fast_feed_data_path = '/remote/iosg/coin-2/feed_cache2/%s/%s/%s'
raw_feed_data_path = '/remote/iosg/coin/data/flow/%s/%s/%s/'
symbol_group_path = f'{git_root_path}/data/coin2/feed/symbol_groups.toml'



def to_snake_mea(mea):
    mea_list= mea.split('.')
    return '_'.join([mea_list[0].lower(), mea_list[1].lower(), mea_list[2].lower()])

def format_mea(mea: str):
    if '.' in mea:
        mea = mea.split('.')
    elif '_' in mea:
        mea = mea.split('_')
    mea[0] = mea[0].title()
    mea[1] = mea[1].title()
    mea[2] = mea[2].lower()
    return '.'.join([mea[0],mea[1],mea[2]])

def get_symbol_group(path = symbol_group_path):
    path = f'{git_root_path}/data/coin2/feed/symbol_groups.toml'
    with open(path, 'r') as f:
        symbol_groups = toml.load(f)
    return symbol_groups

def set_engine(db_config: dict = coin2_feed_stats_importer_config):
    host = db_config['host']
    port = '3306'
    db = db_config['database']
    user = db_config['user']
    passwd = db_config['password']
    engine_name = 'mysql+mysqldb://%s:%s@%s:%s/%s' % (
        user, passwd, host, port, db)
    engine = create_engine(engine_name)
    return engine

def load_from_db(date):
    # select symbol,machine,mea
    query = '''SELECT t1.symbol,t1.machine,t2.market_type,t2.exchange,t2.api_version FROM FeedHealthStats as t1
    JOIN ExchangeAPI as t2 ON t1.exchange_api_id = t2.exchange_api_id
    WHERE t1.trading_date = '%s'
    ORDER BY t1.exchange_api_id;'''
    engine = set_engine()
    symbols_info = pd.read_sql(query % date, engine)
    # symbols_info.drop_duplicates(
    #     subset=['symbol', 'market_type', 'exchange'], inplace=True)
    symbols_info = symbols_info.reset_index()
    del symbols_info['index']
    if len(symbols_info) > 0:
        symbols_info['mea'] = symbols_info.apply(lambda row: '.'.join([row['market_type'], row['exchange'], row['api_version']]), axis=1)
    return symbols_info


def datetime_to_str(func):
    def transform(*args, **kw):
       dt = func(*args, **kw)
       return dt.strftime('%Y%m%d')
    return transform

@datetime_to_str
def to_absolute_week(date,next_num):
  date = date + timedelta(weeks=next_num)
  days_to_friday = (4 - date.weekday()) % 7
  return date + timedelta(days=days_to_friday)

@datetime_to_str
def to_absolute_month(date,next_num):
  date = date + relativedelta(months=next_num+1)
  last_day_of_month = datetime(date.year, date.month, 1) - timedelta(days=1) 
  days_to_friday = (7 - (4 - last_day_of_month.weekday()) % 7) %7
  return last_day_of_month - timedelta(days=days_to_friday)

@datetime_to_str
def to_absolute_quarter(date,next_num):
  date = date + relativedelta(months=next_num*3)
  quarter = (date.month - 1) // 3 + 1
  last_month_of_quarter = quarter * 3
  return to_absolute_month(datetime(date.year,last_month_of_quarter,1),0)

@datetime_to_str
def to_absolute_day(date,next_num):
  return date + timedelta(days=next_num)



